package com.work.cloudseata.controller;

import com.work.cloudseata.entity.Role;
import com.work.cloudseata.entity.UserRole;
import com.work.cloudseata.repository.RoleRepository;
import com.work.cloudseata.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/permission")
@RestController
public class PermissionController {

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private RoleRepository roleRepository;

    @PostMapping("/bind-default-role")
    public void bindDefaultRole(@RequestParam Long userId) {
        UserRole entity = new UserRole();
        entity.setUserId(userId);
        entity.setRoleId(2);
        userRoleRepository.save(entity);
    }

    @GetMapping("/get-role-code")
    public String getUserRoleCode(@RequestParam Long userId) {
        UserRole entity = userRoleRepository.findByUserId(userId);
        if (entity == null) {
            throw new RuntimeException("用户不存在角色");
        }
        Role role = roleRepository.findById(entity.getRoleId()).orElse(null);
        if (role == null) {
            throw new RuntimeException("用户不存在角色");
        }
        return role.getRoleCode();
    }

    @PostMapping("/upgrade-to-admin")
    public void upgradeToAdmin(@RequestParam Long userId) {
        UserRole entity = userRoleRepository.findByUserId(userId);
        if (entity == null) {
            throw new RuntimeException("用户不存在");
        }
        entity.setRoleId(3);
        userRoleRepository.save(entity);
    }

    @PostMapping("/downgrade-to-user")
    public void downgradeToUser(@RequestParam Long userId) {
        UserRole entity = userRoleRepository.findByUserId(userId);
        if (entity == null) {
            throw new RuntimeException("用户不存在");
        }
        entity.setRoleId(2);
        userRoleRepository.save(entity);
    }

    @GetMapping("/role-user-list")
    public List<Long> roleUserList() {
        return userRoleRepository.findByRoleId(2)
                .stream()
                .map(UserRole::getUserId)
                .toList();
    }
}
